package com.aier.common.common;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

/**
 * @author yoUng
 * @description 发送http请求
 * @filename HttpUtil.java
 * @time 2011-6-15 下午05:26:36
 * @version 1.0
 */
public class MessageSend_CXTS {
    
    private static final String URL = "http://xtx.telhk.cn:8888/sms.aspx";            //请求url
    private static final String URL_GMSG = "http://xtx.telhk.cn:8888/callApi.aspx";    //接收上行短信的url
    private static final String USERID = "4266";            //企业id
    private static final String ACCOUNT = "K000265";        //账号
    private static final String PASSWORD = "156203";    //密码
    
    public static String http(String url, Map<String, String> params) {
        URL u = null;
        HttpURLConnection con = null;
        // 构建请求参数
        StringBuffer sb = new StringBuffer();
        if (params != null) {
            for (Entry<String, String> e : params.entrySet()) {
                sb.append(e.getKey());
                sb.append("=");
                sb.append(e.getValue());
                sb.append("&");
            }
        }
        // 尝试发送请求
        try {
            url = url + "?" + java.net.URLEncoder.encode(sb.substring(0, sb.length() - 1),"utf-8");
//            System.out.println("url:"+url);
            u = new URL(url);
            con = (HttpURLConnection) u.openConnection();
            con.setRequestMethod("POST");
            con.setDoOutput(true);
            con.setDoInput(true);
            con.setUseCaches(false);
            con.setRequestProperty("Content-Type",
                    "application/x-www-form-urlencoded");
            OutputStreamWriter osw = new OutputStreamWriter(
                    con.getOutputStream(), "UTF-8");
            osw.write(sb.toString());
            osw.flush();
            osw.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (con != null) {
                con.disconnect();
            }
        }

        // 读取返回内容
        StringBuffer buffer = new StringBuffer();
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(
                    con.getInputStream(), "UTF-8"));
            String temp;
            while ((temp = br.readLine()) != null) {
                buffer.append(temp);
                buffer.append("\n");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
//        System.out.println(buffer.toString());
        return buffer.toString();
    }

    /**
     * 查询余额
     * @throws Exception 
     */
    public static void overage() throws Exception{
        Map<String, String> params = new HashMap<String, String>();
        params.put("action", "overage");
        params.put("userid", USERID);
        params.put("account", ACCOUNT);
        params.put("password", PASSWORD);
        
        String content_return = http(URL,params);
        
        Document dom = DocumentHelper.parseText(content_return);
        Element root = dom.getRootElement();
        String returnstatus = root.element("returnstatus").getText();
        String message = root.element("message").getText();
        String payinfo = root.element("payinfo").getText();
        String overage = root.element("overage").getText();
        String sendTotal = root.element("sendTotal").getText();
        System.out.println("返回状态值:"+returnstatus+",返回信息提示:"+message+",返回支付方式:"+payinfo+",返回已发送条数:"+overage+",返回总点数:"+sendTotal);
    }
    
    /**
     * 发送短信
     */
    public static String sendMessage(String content,String phone)  throws Exception{
        Map<String, String> params = new HashMap<String, String>();
        params.put("action", "send");
        params.put("userid", USERID);
        params.put("account", ACCOUNT);
        params.put("password", PASSWORD);
        params.put("mobile", phone);//全部被叫号码    发信发送的目的号码.多个号码之间用半角逗号隔开 
        params.put("content", content);        //发送内容    短信的内容    
        params.put("sendTime", "");            //定时发送时间    为空表示立即发送，定时发送格式2010-10-24 09:08:10
        params.put("taskName", "");        //任务名称    本次任务 描述100个字以内  可以为空
        params.put("checkcontent", "0");    //是否检查内容包含非法关键字    当设置为1时表示需要检查，默认0为不检查
        params.put("countnumber", "1");        //号码总数量    本次提交的号码总数量
        params.put("mobilenumber", "1");    //手机号码数量    本次提交的手机号码数量
        params.put("telephonenumber", "0");    //小灵通或座机号码数    本次提交的小灵通或座机号码数数量

        String content_return =  http(URL,params);
        
        Document dom = DocumentHelper.parseText(content_return);
        Element root = dom.getRootElement();
        String returnstatus = root.element("returnstatus").getText();
        String message = root.element("message").getText();
        String remainpoint = root.element("remainpoint").getText();
        String taskID = root.element("taskID").getText();
        String successCounts = root.element("successCounts").getText();
        System.out.println("发送短信--返回状态值:"+returnstatus+",返回信息提示:"+message+",返回余额:"+remainpoint+",返回本次任务的序列ID:"+taskID+",成功短信数:"+successCounts);
            
        return "SUCCESS";
    }
    
    /**
     * 检查关键词 (并返回一次过滤后的)
     */
    public static String checkKeyWord(String content) throws Exception{
        Map<String, String> params = new HashMap<String, String>();
        content = content.replace("'", "");
        params.put("action", "checkkeyword");
        params.put("userid", USERID);
        params.put("account", ACCOUNT);
        params.put("password", PASSWORD);
        params.put("content", content);//检测发送内容    需要发送的内容
        
        String content_return =  http(URL,params);
        
        Document dom = DocumentHelper.parseText(content_return);
        Element root = dom.getRootElement();
        String message = root.element("message").getText();
        System.out.println("检查内容:"+content+",返回信息提示:"+message);
        if(message.indexOf("包含屏蔽字符：")>-1){
            String pbmsg = message.split("包含屏蔽字符：")[1];
            content = content.replaceAll(pbmsg, "");            
            return content;
        }
        return "SUCCESS";
    }
    
    /**
     * 过滤信息(去除屏蔽字符)
     */
    public static String getCheckWord(String content) throws Exception{
        System.out.println("原内容:"+content);
        String return_content = content;
        content = checkKeyWord(content);
        while (!"SUCCESS".equals(content)) {
            return_content = content;
            content = checkKeyWord(content);
        }
        System.out.println("过滤后的内容:"+return_content);
        return return_content;
    }
    
    
    
    /**
     * 接收上行短信
     * @throws Exception 
     */
    @SuppressWarnings("unchecked")
    public static List<List<String>> queryGetMessage() throws Exception{
        List<List<String>> pmList = new ArrayList<List<String>>();
        Map<String, String> params = new HashMap<String, String>();
        params.put("action", "query");
        params.put("userid", USERID);
        params.put("account", ACCOUNT);
        params.put("password", PASSWORD);
        
        String content_return = http(URL_GMSG,params);
        Document dom = DocumentHelper.parseText(content_return);
        Element root = dom.getRootElement();
        Element errorstatus = root.element("errorstatus");
        if(errorstatus!=null){
            String error_id = errorstatus.element("error").getText();
            String error_remark = errorstatus.element("remark").getText();
            System.out.println("接收短信出现错误:错误码为"+error_id+",错误描述为"+error_remark);
        }
        
        List<Element> callboxList = root.elements("callbox");
        if(callboxList!=null && callboxList.size()>0){
            for(Element cb:callboxList){
                String mobile = cb.element("mobile").getText();
                String content = cb.element("content").getText();
                List<String> pml = new ArrayList<String>();
                pml.add(mobile);
                pml.add(content);
                pmList.add(pml);
            }    
        }
        return pmList;
    }
    
    
    public static void main(String[] args) {
        try {
            String phone = "15380479973";
            String content = "班 级公告:国庆过了好几天了，小朋友有没有把小手的指甲剪干净了啊？！另外天气变化无常，注意增减衣服哦！8号正常上课哦！ --朱 琳老 师";

            //查询余额
            overage();
            //内容过滤
            content = getCheckWord(content);
            //发送短信
            sendMessage(content,phone);
            //接收上行短信
            List<List<String>> pmList = queryGetMessage();
            if(pmList.size()>0){
                for(List<String> pm:pmList){
                    System.out.println("接收到短信-手机号:"+pm.get(0)+",内容:"+pm.get(1));
                }
            }else{
                System.out.println("未接收到短信");
            }
            

        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
